package com.dily.study.user.handle;

import com.alibaba.fastjson.JSON;
import com.dily.scaffold.common.reponse.BaseResponse;
import com.dily.study.user.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Date: 2022-06-14 星期二
 * Time: 11:01
 * Author: Dily_Su
 * Remark:
 * 认证和授权，自定义异常处理
 */
@Component
public class AuthenticationHandle implements AuthenticationEntryPoint, AccessDeniedHandler {

    /**
     * 认证失败
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        // 处理异常
        BaseResponse<?> result = BaseResponse.fail(HttpStatus.UNAUTHORIZED.value(), "认证失败请重新登录");
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response, json);
    }

    /**
     * 授权失败
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        // 授权失败
        BaseResponse<?> result = BaseResponse.fail(HttpStatus.FORBIDDEN.value(), "权限不足");
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response, json);
    }
}
